﻿using Consul;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Qzb.MicroService.Common.ConsulExtensions.Register
{
    public class ConsulRegister : IConsulRegister
    {
        private readonly ConsulRegisterOptions _options;

        public ConsulRegister(IOptionsMonitor<ConsulRegisterOptions> options)
        {
            _options = options.CurrentValue;
        }

        public async Task ServiceRegister()
        {
            using ConsulClient client = GetClient();

            var registration = new AgentServiceRegistration()
            {
                ID = GetServiceID(), // 服务唯一Id
                Name = _options.ServiceName, // 服务名
                Address = _options.ServiceIP,
                Port = _options.ServicePort,
                Tags = new string[] { _options.Tag ?? "1" },
                Check = new AgentServiceCheck()
                {
                    HTTP = $"http://{_options.ServiceIP}:{_options.ServicePort}{_options.HealthCheckApiPath}",
                    Interval = TimeSpan.FromSeconds(_options.Interval ?? 5),
                    Timeout = TimeSpan.FromSeconds(_options.Timeout ?? 3),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(_options.DeregisterCriticalServiceAfter ?? 10),
                }
            };

            await client.Agent.ServiceRegister(registration);
            Console.WriteLine($"Consul服务注册：{JsonConvert.SerializeObject(_options)}");
        }

        public async Task ServiceDeregister()
        {
            using ConsulClient client = GetClient();

            var serviceId = GetServiceID();

            await client.Agent.ServiceDeregister(serviceId);
            Console.WriteLine($"Consul服务注销：{serviceId}");
        }

        private ConsulClient GetClient() => new(c =>
        {
            c.Address = new Uri($"http://{_options.ConsulIP}:{_options.ConsulPort}/");
            c.Datacenter = _options.DataCenter;
        });

        private string GetServiceID() => $"{_options.ServiceName}@{_options.ServiceIP}:{_options.ServicePort}";
    }
}
